import axios from 'axios';
import utils from 'axios/lib/utils';
import normalizeHeaderName from 'axios/lib/helpers/normalizeHeaderName';
import createError from 'axios/lib/core/createError';
import buildUrl from 'axios/lib/helpers/buildURL';
import settle from 'axios/lib/core/settle';
// import Timeout from './await-timeout';
// import { cacheAdapterEnhancer } from 'axios-extensions';
//import {LRUCache} from 'lru-cache'

// console.log(cacheAdapterEnhancer)
 
function createAxios(defaultConfig) {
	console.log(defaultConfig)
	let timer = null;
	
	console.log(defaultConfig)
	
	let _axios = axios.create(defaultConfig?defaultConfig:{});
	
	function setContentTypeIfUnset(headers, value) {
	  if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
	    headers['Content-Type'] = value;
	  }
	}
	
	_axios.defaults.transformRequest = [
	  function transformRequest(data, headers) {
	    normalizeHeaderName(headers, 'Accept');
	    normalizeHeaderName(headers, 'Content-Type');
	    if (
	      utils.isFormData(data) ||
	      utils.isArrayBuffer(data) ||
	      utils.isBuffer(data) ||
	      utils.isStream(data) ||
	      utils.isFile(data) ||
	      utils.isBlob(data)
	    ) {
	      return data;
	    }
	    if (utils.isArrayBufferView(data)) {
	      return data.buffer;
	    }
	    if (utils.isURLSearchParams(data)) {
	      setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
	      return data.toString();
	    }
	    if (utils.isObject(data)) {
	      setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
	      return JSON.stringify(data);
	    }
	    return data;
	  }
	];
	
	_axios.defaults.adapter = config => {
	  return new Promise((resolve, reject) => {
	    const requestMethod = (utils.isString(config.method) ? config.method : 'GET').toUpperCase();
	    let requestUrl = config.url.startsWith('http')? '' : config.baseURL 
		requestUrl += buildUrl(config.url, config.params, config.paramsSerializer);
	    const requestHeaders = utils.isObject(config.headers) ? config.headers : {};
	
		console.log(requestUrl)
		
	    // 请求数据
	    let requestData = config.data;
	
	    let request = '';
	    if (requestHeaders['Content-Type'] && requestHeaders['Content-Type'] === 'multipart/form-data') {
	      let data = JSON.parse(config.data);
	      let header = JSON.parse(JSON.stringify(requestHeaders));
	      delete header['Content-Type'];
	      request = uni.uploadFile({
	        url: requestUrl,
	        header: header,
	        filePath: data.content,
	        formData: {
	          type: data.type
	        },
	        name: 'content',
	        success: res => {
	          settle(resolve, reject, {
	            data: res.data,
	            status: res.statusCode,
	            statusText: '',
	            headers: res.header,
	            config: config,
	            request: request
	          });
	        },
	        fail: res => {
	          const error = createError('网络错误', config, res, request);
	          console.log(res)
			  reject(error);
	        },
	        complete: () => {
				if(timer) clearTimeout(timer),timer = null
	        }
	      });
	    } else {
	      request = uni.request({
	        method: requestMethod,
	        url: requestUrl,
	        header: requestHeaders,
	        data: requestMethod === 'POST' || requestMethod === 'PUT' || requestMethod === 'PATCH' ? requestData : '',
	        responseType: config.responseType === 'arraybuffer' ? 'arraybuffer' : 'text',
	        dataType: config.responseType === 'json' ? 'json' : config.responseType,
	        success: res => {
				
			  console.log('请求返回...')
			  if(!!!res.data || res.data == '')
			  {
				  const error = createError('网络空响应', config, res, request);
				  reject(error);
				  return 
			  }
			  
	          settle(resolve, reject, {
	            data: res.data,
	            status: res.statusCode,
	            statusText: '',
	            headers: res.header,
	            config: config,
	            request: request
	          });
			  
			  console.log('请求返回...处理完成.')
	        },
	        fail: res => {
	          const error = createError('网络错误', config, res, request);
	          reject(error);
	        },
	        complete: () => {
	          if(timer) clearTimeout(timer),timer = null
	        }
	      });
	    }
	
	    // 支持超时处理
	    if (config.timeout) {
			timer = setTimeout(()=>{
				timer = null
				reject(new Error('请求超时'));
				request.abort();
			},config.timeout)
	    }
	  });
	};
	
	// _axios.defaults.adapter = cacheAdapterEnhancer(_axios.defaults.adapter,{ 
	// 	enabledByDefault: false ,
	// 	defaultCache: new LRUCache({max:5,ttl:1 * 60 *  1000})
	// })
	
	return _axios
}

export default createAxios;
